package org.lq.shopping.util;

import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Map;

import org.apache.commons.mail.Email;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.HtmlEmail;
import org.lq.shopping.bo.MailInfo;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
/**
 * 发送电子邮件
 * @author linne
 *
 */
public class SendEmail {
	
	private static String  mailServerHost="smtp.163.com";
	private static String  mailServerAddress="ypl-3385807@163.com";
	private static String  mailUserName="ypl-3385807";
	private static String  mailPassword="3385807";
	
	private static HtmlEmail email;
	static {
		email = new HtmlEmail();
		email.setHostName(mailServerHost);
		email.setAuthentication(mailUserName, mailPassword);
		email.setCharset("utf-8");
		
	}
	
	/**
	 * 发送电子邮件 (html格式的)
	 * @param info
	 */
	public static void sentToEmail(MailInfo info,Map<String, Object> rootMap) {
		
		String baseURL = SendEmail.class.getClassLoader().getResource("").getFile();
		
		try {
			email.setFrom(mailServerAddress);
 			String bg1= email.embed(new File(baseURL+"/temple/mmsgletter_2_bg.png"));
 			String bg2= email.embed(new File(baseURL+"/temple/mmsgletter_2_bg_topline.png"));
 			
 			rootMap.put("bg1", bg1);
 			rootMap.put("bg2", bg2);
 			
			String html= getHTML("index.ftl", rootMap);
			
			email.setSubject(info.getSubject());
			email.setHtmlMsg(html);
			email.addTo(info.getToAddress());
			email.send();
			
		} catch (EmailException e) {
			e.printStackTrace();
		}
	}
	
	public static String getHTML(String templeName,Map<String,Object> rootMap) {
		String baseURL = SendEmail.class.getClassLoader().getResource("").getFile();
		StringWriter html = new StringWriter();
		try {
			Configuration cfg = new Configuration();
			//指定对象模板存放的位置
			cfg.setDirectoryForTemplateLoading(new File(baseURL+"/temple"));
			//设置字符集
			cfg.setDefaultEncoding("utf-8");

			Template template = cfg.getTemplate(templeName);
			template.process(rootMap, html);
		} catch (IOException e) {
			e.printStackTrace();
		} catch (TemplateException e) {
			e.printStackTrace();
		}
		
		return html.toString();
	}

}
